package com.moodincode.taskcenter.config;

import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;


/**
 * quartz配置类
 * @author moodincode
 */
@Configuration
public class QuartzConfiguration {

    /**
     * 配置任务工厂实例
     * @param capableBeanFactory spring bean管理工厂，能让Spring管理的Bean去装配和填充那些不被Spring托管的Bean
     * @return
     */
    @Bean
    public JobFactory jobFactory(AutowireCapableBeanFactory capableBeanFactory) {
        return new AdaptableJobFactory() {
            @Override
            protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
                Object jobInstance = super.createJobInstance(bundle);
                capableBeanFactory.autowireBean(jobInstance);
                return jobInstance;
            }
        };
    }

    /**
     * 配置quartz任务调度工厂bean对象
     * @param jobFactory  任务管理工厂，有上面定义
     * @return
     * @throws Exception
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws Exception {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        //将spring管理job自定义工厂交由调度器维护
        schedulerFactoryBean.setJobFactory(jobFactory);
        //设置是否覆盖已存在的任务
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        //项目启动完成后，等待5秒后开始执行调度器初始化
        schedulerFactoryBean.setStartupDelay(5);
        //设置调度器自动运行
        schedulerFactoryBean.setAutoStartup(true);
        //设置上下文spring bean name
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
        //数据源设置，可注入springboot管理的DataSource
        // schedulerFactoryBean.setDataSource(dataSource);
        //读取quartz.properties配置文件中的配置
        //schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
        return schedulerFactoryBean;
    }
}